package com.du.linandroid.biz;

import android.app.Activity;
import android.os.Bundle;


import com.du.linandroid.util.Constant;
import com.du.linandroid.util.LLog;
import com.du.linandroid.util.Util;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by DuZiLin on 2018/3/29.
 */

public class WxCallbackActivity extends Activity implements IWXAPIEventHandler {
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;
    private OkHttpClient client = new OkHttpClient.Builder().build();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //如果没回调onResp，八成是这句没有写
        ApiHolder.mWxApi.handleIntent(getIntent(), this);

    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        LLog.d("errCode:" + baseResp.errCode);
        LLog.d("type : " + baseResp.getType());
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                LLog.d("用户拒绝登录");
                WechatService.mLoginCallBack.fail(Util.getFailJson(BaseResp.ErrCode.ERR_AUTH_DENIED +"", "用户拒绝登录"));
                WechatService.mLoginCallBack.complete();
                WxCallbackActivity.this.finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:

                if(baseResp.getType() == 1){
                    WechatService.mLoginCallBack.fail(Util.getFailJson(BaseResp.ErrCode.ERR_USER_CANCEL +"", "用户取消登录"));
                    WechatService.mLoginCallBack.complete();
                }else if(baseResp.getType() == 2){
                    WXShare.mShareCallBack.fail(Util.getFailJson(BaseResp.ErrCode.ERR_USER_CANCEL +"" , "用户取消分享"));
                }
                WxCallbackActivity.this.finish();
                break;
            case BaseResp.ErrCode.ERR_OK:

                if(baseResp.getType() == 1){
                    LLog.d("准备获取AccessToken");
                    String code = ((SendAuth.Resp) baseResp).code;
                    getAccessToken(code);
                }else if(baseResp.getType() == 2){
                    WXShare.mShareCallBack.success(Util.getFailJson(BaseResp.ErrCode.ERR_OK +"", "分享成功"));
                }
                break;

        }
    }

    private void getAccessToken(String code) {
        Request request = new Request.Builder().url("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ ApiHolder.WX_APP_ID +"&secret=" + ApiHolder.WX_SECRET + "&code=" + code + "&grant_type=authorization_code").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LLog.d(e.getLocalizedMessage());
                LLog.d("onFailure");
                WechatService.mLoginCallBack.fail(Util.getFailJson(Constant.GET_ACCESS_TOKEN_FAILED_CODE ,Constant.GET_ACCESS_TOKEN_FAILED_STR));
                WechatService.mLoginCallBack.complete();
                WxCallbackActivity.this.finish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    getUserInfo(new JSONObject(response.body().string()));
                } catch (JSONException e) {
                    e.printStackTrace();
                    WechatService.mLoginCallBack.fail(Util.getFailJson(Constant.GET_ACCESS_TOKEN_FAILED_CODE ,Constant.GET_ACCESS_TOKEN_FAILED_STR));
                    WechatService.mLoginCallBack.complete();
                    WxCallbackActivity.this.finish();
                }
            }
        });
    }

    private void getUserInfo(JSONObject jsonObject) {

        Request request = new Request.Builder().url("https://api.weixin.qq.com/sns/userinfo?access_token=" + jsonObject.optString("access_token") + "&openid="+jsonObject.optString("openid")).build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                WechatService.mLoginCallBack.fail(Util.getFailJson(Constant.GET_WX_USERINFO_FAILED_CODE ,Constant.GET_WX_USERINFO_FAILED_STR));
                WechatService.mLoginCallBack.complete();
                WxCallbackActivity.this.finish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    WechatService.mLoginCallBack.success(new JSONObject(response.body().string()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }finally {
                    WechatService.mLoginCallBack.complete();
                    WxCallbackActivity.this.finish();
                }
            }
        });
    }
}
